package com.net.shop.car.manager.ui.viewholder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.view.View;
import android.widget.TextView;

import com.net.shop.car.manager.App;
import com.net.shop.car.manager.BaseActivity;
import com.net.shop.car.manager.R;
import com.net.shop.car.manager.api.model.Goods;
import com.net.shop.car.manager.api.volley.VolleyCenter;
import com.net.shop.car.manager.api.volley.VolleyListenerImpl;
import com.net.shop.car.manager.api.volley.request.GetPayType;
import com.net.shop.car.manager.api.volley.response.pay.GetPayTypeResponse;
import com.net.shop.car.manager.ui.payment.PaymentDialog;
import com.net.shop.car.manager.utils.StringUtils;

public class JieSuanViewHolder {
	private View view;
	private TextView price;
	private TextView payBtn;
	private List<Goods> myShopCar = new ArrayList<Goods>();
	private BigDecimal moneyAll;
	private BaseActivity baseActivity;

	public JieSuanViewHolder(View view,final BaseActivity baseActivity) {
		this.view = view;
		price = (TextView) view.findViewById(R.id.jiesuan_mony);
		payBtn = (TextView) view.findViewById(R.id.jiesuan_pay_btn);
		this.baseActivity = baseActivity;
		payBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showPay();
			}
		});
		computeGoodsPrice();
	}
	
	/**
	 * 
	 */
	private void showPay() {
		if(App.i().getUser() == null || App.i().needLogin) {
			baseActivity.gotoLogin();
			return;
		}
		baseActivity.progressDialog.show();
		VolleyCenter.getVolley().addGetRequest(new GetPayType(App.i().getUser().getMemberId()), 
				new VolleyListenerImpl<GetPayTypeResponse>(new GetPayTypeResponse()) {

					@Override
					public void deleveryResponse(GetPayTypeResponse response) {
						baseActivity.progressDialog.dismiss();
						if (response.isSuccess()) {
							PaymentDialog paymentDialog = new PaymentDialog(baseActivity);
							paymentDialog.setPaymentGoods(myShopCar);
							paymentDialog.setPayType( response.getVb(), response.getPayTypes());
							paymentDialog.show();
						}
					}
		});
		
	}
	
	public void setVisibility(int visibility) {
		view.setVisibility(visibility);
	}

	/**
	 * @return the moneyAll
	 */
	public BigDecimal getMoneyAll() {
		return moneyAll;
	}
	
	private void computeGoodsPrice() {
		moneyAll= new BigDecimal(0);
		for (Goods goods : myShopCar) {
			moneyAll = moneyAll.add(goods.getCheapPrice());
		}
		if (moneyAll.doubleValue() > 0) {
			setVisibility(View.VISIBLE);
		} else {
			setVisibility(View.GONE);
		}
		price.setText(StringUtils.parseMoney(moneyAll));
	}
	
	public void addGoods(Goods goods) {
		if (!myShopCar.contains(goods)) {
			myShopCar.add(goods);
		} else {
			myShopCar.remove(goods);
		}
		computeGoodsPrice();
	}

}
